import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/Home/MyHome.vue'//首页要全局

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/login',
    name: 'login',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Login/MyLogin.vue')//按需导入
  },
  {
    path: '/cart',
    name: 'cart',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Cart/MyCart.vue')//按需导入
  },
  {
    path: '/order',
    name: 'order',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Order/MyOrder.vue')//按需导入
  },
  {
    path: '/detail',
    name: 'detail',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Detail/MyDetail.vue')//按需导入
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About/MyAbout.vue')//按需导入
  },

]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL), routes
});
router.beforeEach((to, from, next) => {
  const requiresAuth = ['/cart', '/order']; // 需要认证的路径
  const token = sessionStorage.getItem('token');

  if (requiresAuth.includes(to.path) && !token ) {
    next({ path: '/login', query: { redirect: to.path } });
  } else {
    if(to.path !=="/login" && to.path !=="/" &&  to.path !=="/detail"){
      console.log(to.path)
   sessionStorage.removeItem('aa');
    next();
    sessionStorage.setItem('aa', to.path);
    }
    else {
      next()
    }
  }
});

export default router
